/*
The MIT License (MIT)
Copyright (c) 2013 Dalvik Boss dalvikboss@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package sidl.generator.xcode;

import sidl.Func;
import sidl.Param;
import sidl.Type;
import sidl.generator.GeneratorContext;

public class XCodeAgentImplementationGenerator extends XCodeGenerator {

	public XCodeAgentImplementationGenerator(GeneratorContext context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doGenerateXCode() throws Throwable {
		generateAgent();

	}
	
	private void generateAgent() {
		println("@implementation %s_%s_Agent", doc.cPackageName(), doc.mainInf().name);
		for(Func f: doc.mainInf().funcs) {
			generateMethod(f);
		}
		generateConstruct();
		println("@end");		
	}

	private void generateMethod(Func f) {
		println("-(%s) %s %s", f.rtype.asReturnTypeOfObjc(doc), f.name, getFormalParams(f));
		println("{");
		println("    int _client_fd = helper_%s_%s_Agent_connect([[self host] UTF8String], [self port]);",doc.cPackageName(), doc.mainInf().name);
		if(f.rtype.isArray) {
			println("    NSArray* result = NULL;");
		}else if(f.rtype.name.equals("String")) {
			println("    NSString* result = NULL;");

		} else if(f.rtype.isClazz()) {
			println("    %s_%s* result = NULL;",  doc.cPackageName(), f.rtype.name);
		} else if(f.rtype.isPrim()) {
			println("    %s result = 0;", Type.asObjcName(f.rtype.name));
		} 

		println("    if(_client_fd==-1)");
		println("    {");
		println("        @throw [[%s_%s_SidlExecption alloc] initWith:@\"connect service failed\"];",doc.cPackageName(), doc.mainInf().name);
		println("    }");
		
		println("    @try");
		println("    {");
		println("        ByteBuffer *_bb = [[ByteBuffer alloc] init];");
	    println("        [_bb put_int:0];//pading for packet len");
	    println("        [_bb put_sidl_long:AgentID.low];");
	    println("        [_bb put_sidl_long:AgentID.high];");
		println("        [_bb put_int:IO_INVOKE];");

		println("        [_bb put_int:ft_%s];", f.name);
		for(Param p: f.params) {
			if(p.type.isArray) {
				println("        [_bb put_%s_array :%s];", Type.asObjcName(p.type.name), Type.asObjcName(p.name));
			} else {
				println("        [_bb put_%s :%s];", Type.asObjcName(p.type.name), Type.asObjcName(p.name));
			}
		}
		println("        [_bb flip];");
		println("        [_bb net_send: _client_fd];");
		println("        [_bb reset];");
		println("        [_bb net_recv: _client_fd];");
		println("        [_bb flip];");
		println("        %s_RemoteThrowable *_remoteThrowable = [_bb get_RemoteThrowable];", doc.cPackageName());
		println("        if(_remoteThrowable)");
		println("        {");
		println("            @throw [[%s_%s_SidlExecption alloc] initWith:[_remoteThrowable message]];",doc.cPackageName(), doc.mainInf().name);
		println("        } else");
		println("        {");
		if(f.rtype.isArray) {
			println("            result = [_bb get_%s_array];", Type.asObjcName(f.rtype.name));
		} else if(f.rtype.isClazz()) {
			println("            result = [_bb get_%s];",  f.rtype.name);
		} else if(f.rtype.isPrim()) {
			println("            result = [_bb get_%s];",  Type.asObjcName(f.rtype.name));
		}
		println("        }");
		println("    }@catch(%s_%s_SidlExecption *_ex) {", doc.cPackageName(), doc.mainInf().name);
		println("        @throw _ex;");
		println("    }@finally {");
		println("        close(_client_fd);");
		println("    }");
		if(!f.rtype.isVoid()) {
			println("    return result;");

		}
		println("}");
		
	}

	private void generateConstruct() {
		println("-(%s_%s_Agent*) initWith : (NSString*) host :(int) port ", doc.cPackageName(), doc.mainInf().name);
		println("{");
		
		println("    self = [super init];");
		println("    if(self)");
		println("    {");
		println("        [self setHost:host];");
		println("        [self setPort:port];");
		println("    }");
	    println("    sranddev();");
	    println("    for(int i = 0 ; i < sizeof(long long) * 2; i++) {");
	    println("        AgentID.data[i] = rand()%%255;");
	    println("    }");
	    
		println("    return self;");
		
		println("}");
		
	}
	

}
